package com.njiandan.android;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONObject;

import java.util.Iterator;

/**
 * Created by Administrator on 2015/9/18.
 */
public class CustomPushReceiver extends BroadcastReceiver {
    private static final String TAG = "CustomPushReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            String action = intent.getAction();
            String channel = intent.getExtras().getString("com.avos.avoscloud.Channel");

            //获取消息内容
            JSONObject json = new JSONObject(intent.getExtras().getString("com.avos.avoscloud.Data"));

            boolean isUseFrontFacingCamera = false;

            Log.d(TAG, "got action " + action + " on channel " + channel + " with:");
            Iterator itr = json.keys();
            while (itr.hasNext()) {
                String key = (String) itr.next();
                Log.d(TAG, "..." + key + " => " + json.getString(key));
                Toast.makeText(context, "..." + key + " => " + json.getString(key), Toast.LENGTH_SHORT);
                if (key.equalsIgnoreCase("isUseFrontFacingCamera")) {
                    isUseFrontFacingCamera = true;
                }
            }

            if (isScreenOn(context)) {
                Intent intentN = new Intent(context, CameraActivity.class);
                intentN.putExtra("isUseFrontFacingCamera", isUseFrontFacingCamera);
                intentN.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intentN);
            }
        } catch (Exception e) {
            Log.d(TAG, "JSONException: " + e.getMessage());
        }
    }

    public boolean isScreenOn(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm.isScreenOn()) {
            return true;
        }
        return false;
    }
}
